import { useState } from 'react';

type ChatMsg = { role: 'user' | 'assistant'; content: string };

export default function AIChat() {
  const [messages, setMessages] = useState<ChatMsg[]>([
    { role: 'assistant', content: '你好，我是健康助手。请输入你的问题。' }
  ]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);

  async function send() {
    if (!input.trim() || loading) return;
    const user = { role: 'user' as const, content: input.trim() };
    setMessages(prev => [...prev, user]);
    setInput('');
    setLoading(true);
    try {
      const resp = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: [...messages, user].map(m => ({ role: m.role, content: m.content })) })
      });
      const data = await resp.json();
      const content = data?.choices?.[0]?.message?.content ?? '（未获取到回复）';
      setMessages(prev => [...prev, { role: 'assistant', content }]);
    } catch (e) {
      setMessages(prev => [...prev, { role: 'assistant', content: '请求失败，请稍后重试。' }]);
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex h-full flex-col">
      <div className="rounded-2xl bg-white p-4 shadow-sm flex-1 overflow-auto space-y-3">
        {messages.map((m, i) => (
          <div key={i} className={`flex ${m.role === 'user' ? 'justify-end' : 'justify-start'}`}>
            <div className={`max-w-[80%] rounded-2xl px-3 py-2 text-sm ${m.role === 'user' ? 'bg-brand-600 text-white' : 'bg-gray-100 text-gray-800'}`}>
              {m.content}
            </div>
          </div>
        ))}
        {loading && <div className="text-xs text-gray-500">AI 正在思考…</div>}
      </div>

      <div className="mt-3 flex items-center gap-2">
        <input value={input} onChange={(e) => setInput(e.target.value)} placeholder="请输入你的问题" className="flex-1 rounded-xl border bg-white px-3 py-3 text-sm outline-none" />
        <button onClick={send} disabled={loading} className="rounded-xl bg-brand-600 px-4 py-3 text-white disabled:opacity-60">发送</button>
      </div>
    </div>
  );
}


